package hhm.android.machine.weight

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.widget.ImageView
import androidx.activity.result.ActivityResultLauncher
import com.bumptech.glide.Glide
import hhm.android.machine.MachineConnectFailActivity
import hhm.android.machine.MatchSuccessActivity
import hhm.android.machine.R
import siau.android.base.*
import siau.android.http.model.AddMachineRequest
import siau.android.http.model.BluetoothCodeModel
import siau.android.library.KeyString

class BindWeightOneActivity : SBBaseActivity() {

    lateinit var iv: ImageView
    lateinit var startActivityForResult: ActivityResultLauncher<Intent>
    private var bean: MyBlueToothBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_bind_weight_one)

        initTitleWithLine(getString(R.string.seven_bubble_weight_machine))

        startActivityForResult = registerForActivityResult(IntentIntActivityResultContact()) {
            if (it == 1024) {
                setResult(1024)
                finish()
            }
        }

        iv = findViewById(R.id.activity_bind_weight_one_iv)
        Glide.with(this).load(R.mipmap.pairing).into(iv)
    }

    override fun onResume() {
        super.onResume()
        tryStart(true)
    }

    private fun tryStart(first: Boolean) {
        var hasStart = false
        SBApplication.getBlueToothUtils().scanDevices?.forEach {
            if (it.deviceType == 1) {
                hasStart = true
                showLoadingDialog()
                val r = BluetoothCodeModel(it.bluetoothCode)
                HttpHelper().checkCanBindBluetooth(r)?.subscribe({ i ->
                    if (i.isExist == 1) {
                        hideLoadingDialog()
                        showToast(getString(R.string.device_is_bounded))
                        handler.sendEmptyMessageDelayed(1, 500)
                    } else {
                        SBApplication.getBlueToothUtils().setCallback(bCallBack)
                        bean = it
                        SBApplication.getBlueToothUtils().connect(bean, true)
                        handler.sendEmptyMessageDelayed(0, 15000)
                    }
                }, {
                    hideLoadingDialog()
                    showToast(it.message)
                })
                return@forEach
            }
        }
        if (!hasStart && first) {
            SBApplication.getBlueToothUtils().scanDevicesNum?.observe(this, {
                tryStart(false)
            })
        }
    }

    private val bCallBack = object : BlueToothUtil.CallBack {
        override fun hasConnect() {
            hideLoadingDialog()
            goToFailPage()
            showToast("设备已被连接")
        }

        override fun connectSuccess(myBlueToothBean: MyBlueToothBean) {
            if (bean != null && bean!!.bluetoothCode == myBlueToothBean.bluetoothCode) {
                val r = AddMachineRequest(1, myBlueToothBean.bluetoothCode, 1, 0, myBlueToothBean.bluetoothCode, 1, -1)
                HttpHelper().addDevice(r)?.subscribe({
                    SBApplication.userData.footGuide = it.footGuide
                    SBApplication.userData.deviceList = it.deviceList
                    hideLoadingDialog()
                    handler.removeMessages(0)
                    SBApplication.getBlueToothUtils().scanDevices?.clear()
                    SBApplication.getBlueToothUtils().scanDevicesNum?.value = 0
                    SBApplication.getBlueToothUtils().setCallback(null)
                    goToSuccessPage()
                }, {
                    hideLoadingDialog()
                    showToast(it.message)
                })
            }
        }

        override fun connectFail() {
            hideLoadingDialog()
            goToFailPage()
            handler.removeCallbacksAndMessages(null)
            showToast("设备连接失败")
        }
    }

    fun goToFailPage() {
        val i = Intent(this, MachineConnectFailActivity::class.java)
        startActivityForResult.launch(i)
        finish()
    }

    fun goToSuccessPage() {
        val i = Intent(this, MatchSuccessActivity::class.java)
        i.putExtra(KeyString.type, 1)
        startActivityForResult.launch(i)
    }

    override fun finish() {
        SBApplication.getBlueToothUtils().setCallback(null)
        super.finish()
    }

    val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                SBApplication.getBlueToothUtils().cancelConnect()
                hideLoadingDialog()
                goToFailPage()
                showToast("设备连接失败")
            } else if (msg.what == 1) {
                finish()
            }
        }
    }
}